﻿/**
 过滤外链
 同时，修复百科链接
*/
(function(E, $){

var Consts = E.consts,
	reBaike=/^http:\/\/(\w+\.){0,2}(?:hudong|baike|hoodong)\.com/i,
	
	// 0 不过滤；1 过滤
	// 默认过滤外链
	isFilterExternal = (typeof g_filterExternal === "function") ? g_filterExternal: function(){
		return 1;
	};

E.addFilter('baike', {
	replace: function( dom ){
		if(typeof dom !='object' || !dom.body){return dom;}
		var links = E.$('a');
		
		links.each(function(){
			var link = $(this),
				href = link.attr('href'),
				text = link.text();
			
			if (
				 ( link.is('.innerlink,.baikelink') || /www\.(hudong|baike)\.com\/wiki\//i.test( href ) ) 
				&& !reBaike.test(text)
			){
			// 修复百科链接
				link.attr('href', 'http:/'+'/www.baike.com/wiki/' + encodeURI(text) );
			}else if( href && isFilterExternal() ){
				href = href.toLowerCase();
				var pos = href.indexOf(location.hostname);
				E.log('run', '发现链接 '+href);
				
				if( /^\w+:/i.test(href) 
					&& (!reBaike.test(href) && (!location.hostname || pos < 0 || pos > 10) )
				) {
					link.replaceWith(link.html());
					E.log('run', '过滤外链'+href);
				}
			}
		});
		
		// 过滤旧的目录，将div转为h2/3
		E.$('.hdwiki_tmml').each(function(){
			var o = $(this),
				text = o.text();
			o.replaceWith('<h2>'+ text +'</h2>');
		});
		E.$('.hdwiki_tmmll').each(function(){
			var o = $(this),
				text = o.text();
			o.replaceWith('<h3>'+ text +'</h3>');
		});
	}
});

})(jQEditor, jQuery);